<?php

namespace app\index\controller;

use app\index\service\JdUnionService;
use think\Controller;

class JdUnion extends Controller
{
    const PAGE_INDEX = 1;
    const PAGE_SIZE  = 100;

    const TOTAL_PAGE = 200;

    const APP_KEY    = 'f4c29f219e27782f41739a81efe42660';
    const SECRET_KEY = 'dce3ef04bc4d41a7927531251e4e1951';
    const URL        = 'https://router.jd.com/api';

    public function index()
    {
        ini_set('memory_limit', '128M');
        ini_set("max_execution_time", "120");

        $params = [
            // 'eliteId'   => 129,
            'pageSize'  => self::PAGE_SIZE,
            'pageIndex' => self::PAGE_INDEX,
        ];

        $data = self::jingFenQuery($params);
        // 格式化
        $goodsData = (new JdUnionService())->formatData($data);
        // 写入csv中
        $this->exportCsv($goodsData);
    }

    /**
     * 导出CSV文件
     */
    function exportCsv($goodsData)
    {
        // 文件名，这里都要将utf-8编码转为gbk，要不可能出现乱码现象
        $filename = $this->utfToGbk('高佣金榜');

        // 拼接文件信息，这里注意两点
        // 1、字段与字段之间用逗号分隔开
        // 2、行与行之间需要换行符
        $fileData = $this->utfToGbk($this->getTableHeader()) . "\n";

        foreach ($goodsData as $value) {
            $temp = $this->getTableBody($value);

            $fileData .= $this->utfToGbk($temp) . "\n";
        }

        $filePath = __DIR__ . '/' . $filename;
        // 将一个字符串写入文件
        file_put_contents($filePath, $fileData);
        return $filePath;
        //
        // // 头信息设置
        // header("Content-type:text/csv");
        // header("Content-Disposition:attachment;filename=" . $filename . '.csv');
        // header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        // header('Expires:0');
        // header('Pragma:public');
        // echo $fileData;
        // exit;
    }

    /**
     * 表头 逗号分隔
     * @return string
     */
    private function getTableHeader()
    {
        return '商品ID, 商品名称, spuid，其值为同款商品的主skuid, 一级分类ID, 一级分类名称, 二级分类ID,二级分类名称,三级分类ID,三级分类名称,评论数,促销佣金,佣金比例,券后佣金（促销价-优惠券面额）*佣金比例,计划结束时间,是否锁定佣金比例,plus佣金比例，plus用户购买推广者能获取到的佣金比例,计划开始时间,京东配送 1：是，0：不是,商品好评率,30天引单数量,30天引单数量(sku维度),商品落地页,是否自营,历史最低价天数（例：当前券后价最近180天最低）,券后价（有无券都返回此字段）,促销价,促销价类型，1：无线价格；2：拼购价格； 3：秒杀价格,商品价格';
    }

    /**
     * 内容,各字段逗号连接
     * @param $data
     */
    public function getTableBody($data)
    {
        return
            '\''.$data['skuId'] . ',' .
            $data['skuName'] . ',' .
            '\''.$data['spuid'] . ',' .
            $data['cid1'] . ',' .
            $data['cid1Name'] . ',' .
            $data['cid2'] . ',' .
            $data['cid2Name'] . ',' .
            $data['cid3'] . ',' .
            $data['cid3Name'] . ',' .
            $data['comments'] . ',' .
            $data['commission'] . ',' .
            $data['commissionShare'] . ',' .
            $data['couponCommission'] . ',' .
            $this->get_microtime_format($data['endTime']) . ',' .
            $data['isLock'] . ',' .
            $data['plusCommissionShare'] . ',' .
            $this->get_microtime_format($data['startTime']) . ',' .
            $data['deliveryType'] . ',' .
            $data['goodCommentsShare'] . ',' .
            $data['inOrderCount30Days'] . ',' .
            $data['inOrderCount30DaysSku'] . ',' .
            $data['materialUrl'] . ',' .
            $this->formatOwner($data['owner']) . ',' .
            $data['historyPriceDay'] . ',' .
            $data['lowestCouponPrice'] . ',' .
            $data['lowestPrice'] . ',' .
            $data['lowestPriceType'] . ',' .
            $data['price'] . ',';
    }

    /**
     * 毫秒时间格式化
     * @param $time
     * @return string
     */
    function get_microtime_format($time)
    {
        $tag  = 'Y-m-d H:i:s';
        $a    = substr($time, 0, 10);
        $b    = substr($time, 10);
        $date = date($tag, $a) . '.' . $b;
        return $date;
    }

    private function formatOwner($owner)
    {
        if ($owner == 'g') {
            $str = '自营';
        } else {
            $str = '非自营';
        }
        return $str;
    }

    /**
     * 字符转换（utf-8 => GBK）
     */
    function utfToGbk($data)
    {
        // return $data;
        return iconv('utf-8', 'GB2312//IGNORE', $data);
    }

    /**
     * 京粉精选商品查询接口
     * https://union.jd.com/openplatform/api/10417
     * @param array $params 见文档的业务入参
     * @return bool|array
     */
    public static function jingFenQuery(array $params)
    {
        $method = 'jd.union.open.goods.jingfen.query';

        // 循环获取
        $result = [];
        for ($j = 1; $j <= 300; $j++) {
            for ($i = 0; $i <= self::TOTAL_PAGE; $i++) {
                $params['pageIndex'] = $i;
                $params['eliteId'] = $j;
                $res = self::query($method, ['goodsReq' => $params]);
                if (isset($res['jd_union_open_goods_jingfen_query_response']) && $res['jd_union_open_goods_jingfen_query_response']['code'] == '0') {
                    $temp = json_decode($res['jd_union_open_goods_jingfen_query_response']['result'], true);
                    if ($temp['code'] == 200) {
                        foreach ($temp['data'] as $key => $value) {
                            $result[] = $value;
                        }
                    } else {
                        continue;
                    }
                } else {
                    continue;
                }
            }
        }

        return $result;
    }

    /**
     * 基础查询方法
     * @param string $method       方法名
     * @param array  $businessData 业务入参
     * @return array
     */
    private static function query($method, array $businessData)
    {
        //业务参数
        $param_json = json_encode($businessData);
        //系统参数
        $system_data = [
            'v'            => '1.0',
            'method'       => $method,
            'access_token' => '',
            'app_key'      => self::APP_KEY,
            'sign_method'  => 'md5',
            'format'       => 'json',
            'timestamp'    => date("Y-m-d H:i:s"),
            'sign'         => '',
            'param_json'   => $param_json,
        ];
        //签名
        $orderData           = self::paramOrder($system_data);
        $sign                = self::paramSign($orderData);
        $system_data['sign'] = $sign;
        return json_decode(self::post($system_data), true);
    }

    //排序ksort
    private static function paramOrder($params)
    {
        ksort($params);
        $stringToBeSigned = "";
        $i                = 0;
        foreach ($params as $k => $v) {
            if (false === self::checkEmpty($v)) {
                $v = self::characet($v, 'utf-8');
                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "$v";
                } else {
                    $stringToBeSigned .= "$k" . "$v";
                }
                $i++;
            }
        }
        unset ($k, $v);
        return $stringToBeSigned;
    }

    //为空检查
    private static function checkEmpty($value)
    {
        if (!isset($value)) {
            return true;
        }
        if ($value === null) {
            return true;
        }
        if (trim($value) === "") {
            return true;
        }
        return false;
    }

    //编码设置
    private static function characet($data, $targetCharset)
    {
        if (!empty($data)) {
            $fileType = 'utf-8';
            if (strcasecmp($fileType, $targetCharset) != 0) {
                $data = mb_convert_encoding($data, $targetCharset, $fileType);
            }
        }
        return $data;
    }

    //签名
    private static function paramSign($params)
    {
        $str  = self::SECRET_KEY . $params . self::SECRET_KEY;
        $sign = md5($str);
        return strtoupper($sign);
    }

    //基于curl提交
    private static function post($param)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, self::URL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}